package mysgoog.bot.algo;

import mysgoog.board.Board;
import mysgoog.gtp.Color;

public class Balance {

	private static final int[] xDiv = { 0, 4, 9, 13 };
	private static final int[] yDiv = { 0, 4, 9, 13 };
	private static final double threshold = 1;
	private static final double inf = 100000.0;

	private static double[][] now = new double[3][3];
	private static Board board;
	private static int maxX;
	private static int maxY;
	private static double maxValue;
	private static Color mycolor;
	private static Color oppcolor;

	static public int balance(Board bd, Color color) {
		board = bd;
		mycolor = color;
		oppcolor = color.complement();

		initial();
		chooseMax();

		if (maxX >= 0 && maxY >= 0) {
			return board.makePos((xDiv[maxX] + xDiv[maxX + 1]) / 2,
					(yDiv[maxY] + yDiv[maxY + 1]) / 2);
		} else
			return -1;
	}

	static private void initial() {
		for (int i = 0; i < 3; ++i) {
			for (int j = 0; j < 3; ++j) {

				int begX = xDiv[i];
				int endX = xDiv[i + 1];
				int begY = yDiv[j];
				int endY = yDiv[j + 1];
				int totalMy = 0;
				int totalOpp = 0;

				for (int k1 = begX; k1 < endX; ++k1) {
					for (int k2 = begY; k2 < endY; ++k2) {
						Color stone = board.getStone(board.makePos(k1, k2));
						if (stone == oppcolor)
							++totalOpp;
						if (stone == mycolor)
							++totalMy;
					}
				}

				if (totalMy == 0 && totalOpp == 0) {
					now[i][j] = inf;
				} else if (totalMy == 0) {
					if (totalOpp <= 3) {
						now[i][j] = inf / (totalOpp + 1);
					} else
						now[i][j] = 0;
				} else if (totalOpp == 0) {
					if (totalMy <= 3) {
						now[i][j] = inf / (totalMy + 1);
					} else
						now[i][j] = 0;
				} else {
					if ((totalMy >= totalOpp && totalMy <= totalOpp * 2)
							|| (totalOpp >= totalMy && totalOpp <= totalMy * 2)) {
						now[i][j] = inf / (totalMy + totalOpp + 1);
					} else {
						now[i][j] = 0;
					}
				}

				if (i == 1 && j == 1) {
					now[i][j] = now[i][j] /3;
				} else if (i == 1 || j == 1) {
					now[i][j] = now[i][j] /2;
				}

			}
		}
	}

	static private void chooseMax() {
		maxX = -1;
		maxY = -1;

		for (int i = 0; i < 3; ++i) {
			for (int j = 0; j < 3; ++j) {
				if (now[i][j] > threshold) {
					if (maxX == -1) {
						maxX = i;
						maxY = j;
						maxValue = now[i][j];
					} else if (maxValue < now[i][j]) {
						maxX = i;
						maxY = j;
						maxValue = now[i][j];
					}
				}
			}
		}
	}

}
